var fs = require('fs');
var path = require('path');
var request = require('request');
var file = path.join(__dirname, 'url.txt');
// var file = path.join(__dirname, 'urlxx.txt');
// http://davidwalsh.name/async-generators 

function getUrl() {
	console.log('getUrl');
	return new Promise(function(fullfil, reject) {
		fs.readFile(file, 'utf8', function(err, res) {
			if (err) reject(err);
			else {
				console.log('url=' + res);
				fullfil(res);
			}
		});
	});
}

function getUrlV2() {
	console.log('getUrlV2');
	return function(cb) {
		fs.readFile(file, 'utf8', function(err, res) {
			cb(res);
		});
	}
}

function makeRequest(url) {
	console.log('makeRequest,url=' + url);
	// url = 'http://haha.foo.bar.com';
	return new Promise(function(fullfil, reject) {
		request(url, function(err, res, body) {
			if (err) reject(err);
			else {
				console.log('makeRequest ok');
				fullfil(body);
			}
		});
	});
}

function* main() {
	console.log('main start');
	var url = yield getUrl();
	// var url = yield getUrlV2(); // ok
	var body = yield makeRequest(url);
	console.log('aaa');
	console.log(body.substring(0, 10));
	console.log('bbb');
}

function runGen(gen) {
	var it = gen();
	var result;
	var count = 0;

	function goNext(val) {
		console.log('goNext count=' + (++count));
		result = it.next(val);

		if (result.done) return;
		var v = result.value;
		if (typeof v === 'function') { // function
			console.log('function');
			v(goNext);
		} else if ('then' in v) { // promise
			console.log('then');
			// v.then(function(res) {
			// 	goNext(res);
			// });
			v.then(goNext);
		} else { // direct value 
			// avoid synchronous recursion ==>学了一招
			console.log('direct value');
			process.nextTick(function() {
				goNext(it.next(v));
			});
		}
	}

	goNext();
}

runGen(main);